/**
 * 
 */
package com.wistech.search.solr.extend;

import java.io.IOException;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.FieldCache;
import org.apache.lucene.search.Filter;
import org.apache.lucene.util.OpenBitSet;

import com.wistech.commons.utils.spring.SpringContextHolder;

/**
 * @author Liuye
 * 
 */
@SuppressWarnings("serial")
public class OnlineFilter extends Filter {
	public static final String FIELD_NAME = "live_online";
	private static final String KEY = "userId";
	private OpenBitSet onlineUserIds = new OpenBitSet();
	private long[] userIdIndex;

	public OnlineFilter() {
		ExternalDataContext context = SpringContextHolder
				.getBean("externalDataContext");
		for (Long userId : context.getOnlineUserIds()) {
			onlineUserIds.set(userId);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.lucene.search.Filter#getDocIdSet(org.apache.lucene.index.
	 * IndexReader)
	 */
	@Override
	public DocIdSet getDocIdSet(IndexReader reader) throws IOException {
		if (onlineUserIds == null || onlineUserIds.isEmpty()) {
			return new OpenBitSet();
		}
		userIdIndex = FieldCache.DEFAULT.getLongs(reader, KEY);
		OpenBitSet bitSet = new OpenBitSet(reader.maxDoc());
		for (int i = 0; i < reader.maxDoc(); i++) {
			if (reader.isDeleted(i))
				continue;
			if (onlineUserIds.get(userIdIndex[i])) {
				bitSet.fastSet(i);
			}
		}
		return bitSet;
	}
}
